import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.google.code.facebookapi.*;
import processing.core.*;


/**
 * Loads images from Facebook in separate Thread.
 */
public class FBLoader implements Runnable {

	private int remaining;
	public PApplet parent;
	private List<ProfileImage> queue;

	public FBLoader(FBConnect c, PApplet p) {
		this.parent = p;
		this.queue = new ArrayList<ProfileImage>();
		this.remaining = 0;
	}

	/**
	 * Download images in queue.
	 */
	@Override
	public void run() {

		Iterator<ProfileImage> it = this.queue.iterator();

		while(it.hasNext()){
			ProfileImage user = it.next();
			ProfileField size = user.getSizeToDownload();

			String url = "";
			PImage pic;

			switch(size){

			case PIC_SQUARE:
				url = user.pic_square_url;
				pic = parent.loadImage(url);
				user.setPic_square(pic);
				break;

			case PIC_BIG:
				url = user.pic_big_url;
				pic = parent.loadImage(url);
				user.setPic_big(pic);
				break;
			}

			System.out.println(this.remaining + ": Downloaded " + url);

			this.remaining--;
		}
	}

	/**
	 * Adds user to download queue.
	 * 
	 * @param user	user to be added to the download queue 
	 * @param size	the size of the image to be downloaded, either small square or full sized profile image
	 */
	public void loadPic(ProfileImage user, ProfileField size){
		user.setSizeToDownload(size);
		this.queue.add(user);
		this.remaining++;
	}

	/**
	 * Loading status as amounts.
	 * 
	 * @return	2-sized array where first number is number of remaining items and second total queue size
	 */
	public int[] loadingStatus(){
		int[] status = {this.remaining, this.queue.size()};
		return status;
	}

	/**
	 * Tells if loader is loading.
	 * 
	 * @return	<code>true</code>, if loading otherwise <code>false</code>
	 */
	public boolean isLoading(){
		if (this.remaining > 0){
			return true;
		} else {
			return false;
		}
	}

}
